package com.byx.chatclient.view.activity.ui.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.byx.chatclient.ChatApp;
import com.byx.chatclient.R;
import com.byx.chatclient.adapter.ConversationAdapter;
import com.byx.chatclient.adapter.SearchFriendAdapter;
import com.byx.chatclient.bean.Group;
import com.byx.chatclient.entity.Constant;
import com.byx.chatclient.entity.Friend;
import com.byx.chatclient.entity.GroupDto;
import com.byx.chatclient.entity.ResultCallback;
import com.byx.chatclient.entity.message.Message;
import com.byx.chatclient.event.EventType;
import com.byx.chatclient.event.MessageEvent;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.http.ActionRequest;
import com.byx.chatclient.model.ChatPo;
import com.byx.chatclient.utils.GsonUtil;
import com.byx.chatclient.utils.ThreadPoolUtil;
import com.byx.chatclient.utils.TimeFormatUtil;
import com.byx.chatclient.view.activity.GroupChatActivity;
import com.byx.chatclient.view.activity.SingleChatActivity;
import com.byx.chatclient.view.activity.main.MainActivity;
import com.byx.chatclient.widget.SearchView;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author Superb
 */
public class HomeFragment extends Fragment {
    private ConversationAdapter mAdapter;
    private SearchFriendAdapter mFriendAdapter;

    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.lv_message_list)
    protected RecyclerView mConversationList;
    @SuppressLint("NonConstantResourceId")
    @BindView(R.id.sv_search_view)
    protected SearchView mSearchView;

//    @SuppressLint("NonConstantResourceId")
//    @BindView(R.id.toolbar_title)
//    protected TextView mTvTitle;
    private Unbinder mUnbinder;

    private Type type;
    private List<ChatPo> chatPoList;
    private boolean needUpdateFile;
    
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        mUnbinder = ButterKnife.bind(this, root);
        initListener();
        type = new TypeToken<List<ChatPo>>(){}.getType();
        ChatApp.CHAT_LIST_FILE = requireContext().getExternalCacheDir().getAbsolutePath() + "/chat/" +
                ChatApp.getInstance().getUserPo().getLoginId() + File.separator + ChatApp.FILE_NAME;
        String json = GsonUtil.readJsonFromFile(ChatApp.CHAT_LIST_FILE);
        if (json != null){
            chatPoList = GsonUtil.getGson().fromJson(json,type);
        }
        return root;
    }

    /**
     * Called immediately after {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}
     * has returned, but before any saved state has been restored in to the view.
     * This gives subclasses a chance to initialize themselves once
     * they know their view hierarchy has been completely created.  The fragment's
     * view hierarchy is not however attached to its parent at this point.
     *
     * @param view               The View returned by {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}.
     * @param savedInstanceState If non-null, this fragment is being re-constructed
     */
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        initToolBar();
        initListAndAdapter();
//        initListener();
        super.onViewCreated(view, savedInstanceState);
    }

    private void initListener() {
        mSearchView.setOnClickListener(v -> {
            ((MainActivity) requireActivity()).showSearchView();
        });
    }

    @SuppressLint("NonConstantResourceId")
    private void initToolBar() {
//        ((TextView) requireActivity().findViewById(R.id.toolbar_title)).setText("消息");
//        ((AppCompatActivity) requireActivity()).setSupportActionBar(mToolbar);
//        mTvTitle.setText("消息");
//        setHasOptionsMenu(true);
        ((MainActivity) requireActivity()).showToolbarMenu();
        ((MainActivity) requireActivity()).showToolbarAvatar();
    }

    private static int dp2px(Context context,float dp){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    private void initListAndAdapter() {
//        RecyclerViewDivider recyclerViewDivider = new RecyclerViewDivider(requireContext());
//        recyclerViewDivider.setHorizontalOffset(dp2px(requireContext(), 58), dp2px(requireContext(), -10));
//        recyclerViewDivider.setDividerColor(Color.GRAY);
//        recyclerViewDivider.setDividerHeight(dp2px(requireContext(), 0.5f));
//        recyclerViewDivider.setShowLastDivider(false);
//        mConversationList.addItemDecoration(recyclerViewDivider);

        mAdapter = new ConversationAdapter(chatPoList);
        mConversationList.setAdapter(mAdapter);
        mConversationList.setLayoutManager(new LinearLayoutManager(requireContext()));
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            ChatPo chatPo = (ChatPo) adapter.getItem(position);
            chatPo.resetMessageCount();
            mAdapter.notifyItemChanged(position);
            Intent intent;
            if (chatPo.getIsSingleChat()){
                RetrofitFactory.getBean(ActionRequest.class).queryFriendDetailInfoByLoginId(ChatApp.getInstance().getUserPo().getId(),chatPo.getSenderId())
                        .enqueue(new ResultCallback<Friend>() {
                            @Override
                            public void onResultSuccess(Friend data) {
                                Intent intent = new Intent(requireContext(),SingleChatActivity.class);
                                intent.putExtra(Constant.INTENT_KEY_FRIEND,data);
                                startActivity(intent);
                            }

                            @Override
                            public void onResultFailure(int code, String msg) {

                            }
                        });
            }else {
                RetrofitFactory.getBean(ActionRequest.class).queryUserGroupDetail(ChatApp.getInstance().getUserPo().getId(),Long.parseLong(chatPo.getSenderId()))
                        .enqueue(new ResultCallback<GroupDto>() {
                            @Override
                            public void onResultSuccess(GroupDto data) {
                                Intent intent = new Intent(requireContext(), GroupChatActivity.class);
                                intent.putExtra(Constant.INTENT_KEY_GROUP,data);
                                startActivity(intent);
                            }

                            @Override
                            public void onResultFailure(int code, String msg) {

                            }
                        });
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent event){
        if (event.getEventType().equals(EventType.SINGLE_CHAT_MSG) || event.getEventType().equals(EventType.GROUP_CHAT_MSG)){
            ChatPo chatPo = new ChatPo();
            Message message = (Message) event.getData();
            chatPo.setAvatar(message.getSenderAvatar());
            chatPo.increaseMessageCount();
            chatPo.setSendTime(TimeFormatUtil.format(message.getSentTime()));
            if (event.getEventType().equals(EventType.SINGLE_CHAT_MSG)){
                // 私聊使用对方id显示
                chatPo.setSenderId(message.getSenderId());
                chatPo.setNickName(message.getSenderId());
                chatPo.setSimpleMessage(message.getBody().toString());
                chatPo.setIsSingleChat(true);
            }else {
                // 群聊显示群号
                chatPo.setSenderId(message.getTargetId());
                chatPo.setNickName(message.getTargetId());
                chatPo.setSimpleMessage(message.getSenderNickName() + ":" + message.getBody().toString());
                chatPo.setIsSingleChat(false);
            }
            int position = mAdapter.hasData(chatPo.getSenderId());
            if (position != -1){
                mAdapter.setData(position, chatPo);
                if (position != 0){
                    Collections.swap(mAdapter.getData(),position,0);
                    mAdapter.notifyItemMoved(position, 0);
                }
            }else {
                mAdapter.addData(0, chatPo);
            }
            needUpdateFile = true;
        }
    }

    /**
     * Called when the view previously created by {@link #onCreateView} has
     * been detached from the fragment.  The next time the fragment needs
     * to be displayed, a new view will be created.  This is called
     * after {@link #onStop()} and before {@link #onDestroy()}.  It is called
     * <em>regardless</em> of whether {@link #onCreateView} returned a
     * non-null view.  Internally it is called after the view's state has
     * been saved but before it has been removed from its parent.
     */
    @Override
    public void onDestroyView() {
        if (needUpdateFile){
            String json = GsonUtil.getGson().toJson(mAdapter.getData(),type);
            ThreadPoolUtil.runInBackground(() -> GsonUtil.writeJsonToFile(json, ChatApp.CHAT_LIST_FILE));
        }
        super.onDestroyView();
        mUnbinder.unbind();
        EventBus.getDefault().unregister(this);
    }
}